<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item>
        <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('search')}}</el-button>-->
        <!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('reset')}}</el-button>-->
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['setting:carousel:add']">{{ $t('add') }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="carouselList">
      <el-table-column label="ID" align="center" prop="id" width="180" />
      <el-table-column label="轮播图类型" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <!--          <dict-tag :options="dict.type.banner_type" :value="scope.row.type"/>-->
          <el-tag v-if="scope.row.type == 0">外部链接</el-tag>
          <el-tag v-if="scope.row.type == 1" type="success">内部链接</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" align="center" prop="activityType" width="100">
        <template slot-scope="scope">
          <div v-if="scope.row.type == 1">
            <dict-tag :options="dict.type.instation_skip" :value="scope.row.activityType" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否启动" align="center" prop="state" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
            :inactive-value="0" @change="switchChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" width="680">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">{{ JSON.parse(scope.row.activityId).name }}</span>
          <span v-else>{{ scope.row.url}}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片地址" align="center" prop="img">
        <template slot-scope="scope">
          <oss-image-preview v-if="scope.row.img" :src="scope.row.img" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('operate')" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['setting:carousel:edit']">{{ $t('edit') }}
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['setting:carousel:edit']">{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改轮播图管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="typeList = [];">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="外链" prop="type">
          <el-radio v-model="form.type" label="0">外链接</el-radio>
          <el-radio v-model="form.type" label="1">内链接</el-radio>
        </el-form-item>
        <el-form-item label="外部链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <dict-select :options='dict.type.instation_skip' v-model="form.activityType" placeholder="请选择类型"
            @change="handleChange" />
        </el-form-item>
        <el-form-item label="类型列表">
          <el-select v-model="activityId" placeholder="请选择" @change="handleChange1" v-loadmore="loadmore">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片地址" prop="img">
          <image-upload :limit="1" v-model="form.img"></image-upload>
        </el-form-item>
        <el-form-item label="活动详情" prop="detail">
          <editor v-model="form.detail" placeholder="请输入活动详情" :height="400" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('ok') }}</el-button>
        <el-button @click="cancel">{{ $t('cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCarousel, delCarousel, listCarousel, typePage, updateCarousel, updateState } from '@/api/setting/carousel'
import DateRangePicker from "@/components/DateRangePicker/index.vue";
import DictSelect from "@/components/DictSelect/index.vue";
import OssImagePreview from "@/components/ImagePreview/oss-image-preview.vue";
import { getDicts } from '@/api/system/dict/data'
import { goodsList } from '@/api/activity/seckill'

export default {
  name: "Carousel",
  components: { OssImagePreview, DictSelect, DateRangePicker },
  dicts: ['activity_type', 'banner_type', 'instation_skip'],
  data() {
    return {
      value: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 轮播图管理表格数据
      carouselList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: '',
      },
      // 添加修改类型列表分页参数
      queryFormPop: {
        pageNum: 1,
        pageSize: 999,
        id: null,
      },
      // 表单参数
      form: {
        type: "0",
        time: null,
      },
      activityId: null,
      // 表单校验
      rules: {
        type: [
          { required: true, message: "轮播类型不能为空", trigger: "change" }
        ],
        img: [
          { required: true, message: "图片地址不能为空", trigger: "change" }
        ],
        value: [
          { required: true, message: "时间不能为空", trigger: "change" }
        ],
      },
      typeList: [],
      total1: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询轮播图管理列表 */
    getList() {
      this.loading = true;
      listCarousel(this.queryParams).then(response => {
        this.carouselList = response.data.records;
        this.total = response.data.total;
        this.carouselList.forEach(element => {
          if (!element.activityId) {
            element.activityId =
              "{\"id\":\"\",\"name\":\"\"}"
          }
        });;

        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        activityType: null,
        activityId: null,
        detail: null,
        img: null,
        type: "0",
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.startDate = this.queryParams.time[0]
      this.queryParams.endDate = this.queryParams.time[1]
      console.log('this.queryParams', this.queryParams)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        ...this.queryParams,
        startTime: null,
        endTime: null,
        time: '',
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      /*       this.form.activityType = null
            this.form.img = null
            this.form.id = null
            this.form.detail = null
             */
      this.activityId = null;
      this.value = '';
      this.title = "添加轮播图管理";
      this.open = true;

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = { ...row }
      if (this.form.activityId) this.activityId = JSON.parse(this.form.activityId).name
      this.form.type = this.form.type + ''
      this.queryFormPop.id = this.form.activityType
      this.queryFormPop.pageSize = 999
      if (this.form.type == 1) this.queryTypeList();
      this.open = true;
      this.title = "修改轮播图管理";
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.type == 0) {
        if (!this.form.url) {
          return this.$modal.msgError("请填写外部链接");
        }
      } else if (this.form.type == 1) {
        console.log(JSON.parse(this.form.activityId)) 
        if (!this.form.activityId) {
          this.form.activityId =
              "{\"id\":\"\",\"name\":\"\"}"
          }
        if (!(JSON.parse(this.form.activityId).id)) {
          return this.$modal.msgError("活动不能为空");
        }
      }
      if (this.form.detail) {
        var hasStyleAttribute = /style="/.test(this.form.detail);
        if (hasStyleAttribute) {
          var modifiedText = this.form.detail.replace(/style="/g, 'style="color: white; ');
          console.log(modifiedText);
        } else {
          var modifiedText = this.form.detail.replace(/<p/g, '<p style="color: white;"');
          console.log(modifiedText);
        }
        this.form.detail = modifiedText;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.detail = JSON.stringify(this.form.detail)
          if (this.form.id != null) {
            updateCarousel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCarousel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('delete-or-not')).then(function () {
        return delCarousel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('delete-success'));
      }).catch(() => {
      });
    },
    switchChange(row) {
      updateState({ id: row.id, state: row.state }).then(res => {
        this.$modal.msgSuccess('修改成功');
        this.getList();
      })
    },
    handleChange(e) {
      this.queryFormPop.pageNum = 1;
      this.activityId = null;
      this.typeList = [];
      this.queryTypeList(this.dict.type.instation_skip[e].raw.dictValue)
      console.log(this.form.activityId)

    },
    handleChange1(e) {
      this.activityId = this.typeList[e].name
      this.form.activityId = JSON.stringify(this.typeList[e])
      console.log(this.form.activityId)
    },
    // 查询内联类型列表
    async queryTypeList(id) {
      if (id) this.queryFormPop.id = id;
      this.queryFormPop.pageSize = 999
      await typePage(this.queryFormPop).then(res => {
        this.typeList.push(...res.data.records)
        this.total1 = res.data.total
      })
    },
    // 触底分页
    loadmore() {
      if (this.total1 != this.typeList.length) {
        this.queryFormPop.pageNum++;
        this.queryTypeList()
      }
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .ql-editor {
  background: #1f2d3d;
  color: #FFFFFF;
}
</style>
